var strFullPath=window.document.location.href;
var strPath=window.document.location.pathname;
var pos=strFullPath.indexOf(strPath);
var prePath=strFullPath.substring(0,pos);
var postPath=strPath.substring(0,strPath.substr(1).indexOf('/')+1);
var basePaths = prePath;
basePaths = prePath + postPath;
//获取当前登录人信息
function getSessionUser() {
    var user ={};
    if(localStorage.getItem("user") != null){
        user = JSON.parse(localStorage.getItem("user"));
    }
    return user;
}

function menuCss(str){
	$(".sidebar-menu").find("li.active").removeClass("active");
	$(".menuInfo").each(function (){
		if($(this).html() == str){
			$(".treeview").each(function (){
				if($(this).hasClass("active")){
					$(this).removeClass("active"); 
				}
				$(this).find("ul").attr("class","treeview-menu");
				$(this).find("ul").css("display","none");
			});
			$(this).parent().parent().addClass("active");
			$(this).parent().parent().parent().addClass("menu-open");
			$(this).parent().parent().parent().css("display","block");
			$(this).parent().parent().parent().parent().addClass("active");
			return;
		}
	});
}


function show(){
	if($("body").hasClass("sidebar-collapse")){
		//$("body").attr("class","skin-blue sidebar-mini sidebar-collapse");
		$("body").removeClass("sidebar-collapse");
	}else{
		//$("body").attr("class","skin-blue sidebar-mini");
		$("body").addClass("sidebar-collapse");
	}
	if($("body").hasClass("sidebar-open")){
		$("body").removeClass("sidebar-open");
	}else{
		$("body").addClass("sidebar-open");
	}
}

function rightMenu(){
	var asideClass=$("#rightMenu").attr("class");
	if(asideClass == "control-sidebar control-sidebar-dark"){
		$("#rightMenu").attr("class","control-sidebar control-sidebar-dark control-sidebar-open");
	}else{
		$("#rightMenu").attr("class","control-sidebar control-sidebar-dark");
	}
}



function flavrShow(msg,url,color,isHref){
	new $.flavr({
	    closeOverlay:true,
	    closeEsc : false,
	    content :msg,
	    buttons : [{text:'确定',style:color}]
	})
}


function flavrShowByTime(msg,urls,color,isHref){
	new $.flavr({ 
		content : msg,
		autoclose:true,
        closeOverlay :true,
        closeEsc : true,
        buttons: [{text:'ok',style:color}],
        timeout : 1500,
        onClose:function (){
        	if(isHref && urls != null){
	    		window.location.href=urls;
	    	}
        }});
}

/**
 * 修改密码初始化
 */
function updetePassword(){
    var html = '<div id="updatePasswordmodal" style="display:none">'
        + '<div class="box-body" style="margin:5px 0 -10px 0">'
        + '<form class="form-horizontal" role="form" id="updatePasswordForm" method="post">'
        + '<div class="form-group">'
        + '<label for="username" class="col-sm-2 control-label text-dark">原密码<span class="text-danger"> *</span></label>'
        + '<div class="col-sm-9">'
        + '<input type="password" class="form-control" id="oldPassword" name="oldPassword" placeholder="">'
        + '</div>'
        + '</div>'
        + '<div class="form-group" id="passwordInfo">'
        + '<label for="password" class="col-sm-2 control-label text-dark">新密码<span class="text-danger"> *</span></label>'
        + '<div class="col-sm-9">'
        + '<input type="password" class="form-control" id="newPassword" name="newPassword">'
        + '</div>'
        + '</div>'
        + '<div class="form-group" id="confirmPasswordInfo">'
        + '<label for="confirmPassword" class="col-sm-2 control-label text-dark">确认密码<span class="text-danger"> *</span></label>'
        + '<div class="col-sm-9">'
        + '<input type="password" class="form-control" id="confirmPassword" name="confirmPassword">'
        + '</div>'
        + '</div>'
        + '</form>'
        + '</div>'
        + '<br/>'
        + '<div class="box-footer text-right">'
        + '<button data-iziModal-close class="btn btn-default">取消</button>&nbsp;&nbsp;&nbsp;'
        + '<button type="button" class="btn btn-primary" style="margin-right:5px;" onclick="updatePasswordSubmit()">保存</button>'
        + '</div>'
        + '<p>'
        + '</div>';

    $("body").append(html);

    /**
     * 修改密码的modal框
     */
    $("#updatePasswordmodal").iziModal({
        title: '修改密码',
        headerColor: '#00c0ef',
        theme: '',  // light
        attached: '', // bottom, top
        icon: null,
        iconText: null,
        iconColor: '',
        rtl: false,
        width: 600,
        padding: 0,
        radius: 3,
        zindex: 100,
        iframe: false,
        iframeHeight: 400,
        iframeURL: null,
        focusInput: false,
        group: '',
        loop: false,
        navigateCaption: true,
        navigateArrows: true, // closeToModal, closeScreenEdge
        history: true,
        restoreDefaultContent: false,
        autoOpen: false, // Boolean, Number
        bodyOverflow: true,
        fullscreen: true,
        openFullscreen: false,
        closeOnEscape: false,
        overlay: true,
        overlayClose: false,
        overlayColor: 'rgba(0, 0, 0, 0.4)',
        timeout: false,
        timeoutProgressbar: false,
        pauseOnHover: false,
        timeoutProgressbarColor: 'rgba(255,255,255,0.5)',
        transitionIn: 'comingIn',
        transitionOut: 'comingOut',
        transitionInOverlay: 'fadeIn',
        transitionOutOverlay: 'fadeOut',
        onFullscreen: function(){},
        onResize: function(){},
        onOpening: function(){
            updatePasswordValidator();
        },
        onOpened: function(){},
        onClosing: function(){
            $('#updatePasswordForm')[0].reset();
            $("#updatePasswordForm").data('bootstrapValidator').destroy();
        },
        onClosed: function(){
        }
    });
    $("#updatePasswordmodal").iziModal("open",this);
}


/**
 * 修改密码校验
 * @returns
 */
function updatePasswordValidator(){
    $('#updatePasswordForm').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            oldPassword: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },stringLength: {
                        max: 16,
                        message: '最多输入16个字符'
                    }
                }
            },
            newPassword: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },stringLength: {
                        max: 16,
                        message: '最多输入16个字符'
                    }
                }
            },
            confirmPassword:{
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    stringLength:{
                        max: 16,
                        message: '最多输入16个字符'
                    },
                    identical:{
                        field: 'newPassword',
                        message: '两次密码不相同'
                    }
                }
            }
        }
    });
}


/**
 * 修改密码提交
 */
var updatePasswordBool = false;
function updatePasswordSubmit(){
    if(updatePasswordBool == false){
        $('#updatePasswordForm').bootstrapValidator('validate');
        if($('#updatePasswordForm').data('bootstrapValidator').isValid()){
            updatePasswordBool = true;
            var url = $("#baseUrl").val();
            url = url + "/user/updatePassword";
            $.ajax({
                type : "POST",
                url : url,
                data :$('#updatePasswordForm').serialize(),//整个表单提交
                dataType : "json",
                success : function(data) {
                    try {
                        if(data.ret == 200){
                            flavrShowByTime(data.msg,null,"success",false);
                            $("#updatePasswordmodal").iziModal("close",this);
                        }else{
                            flavrShowByTime(data.msg,null,"danger",false);
                        }
                        updatePasswordBool = false;
                    } catch (error) {
                        flavrShowByTime(data.msg,null,"danger",false);
                        updatePasswordBool = false;
                    }
                },
                failure : function() {
                    flavrShowByTime(data.msg,null,"danger",false);
                    updatePasswordBool = false;
                }
            });
        }
    }
}

function logout(){
    var baseUrl = $("#baseUrl").val();
    var url = baseUrl + "/user/logout";
    $.ajax({
        type : "POST",
        url : url,
        dataType : "json",
        success : function(data) {
            try {
                if(data.ret == 200){
                	location.href=baseUrl+"/login.html";
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                }
                updatePasswordBool = false;
            } catch (error) {
                flavrShowByTime(data.msg,null,"danger",false);
                updatePasswordBool = false;
            }
        },
        failure : function() {
            flavrShowByTime(data.msg,null,"danger",false);
            updatePasswordBool = false;
        }
    });
}

function publicAjax(url,type,parameter,fn){
    var basePath = $("#basePath").val();
    if($("body").find("[name='request-div']")){
        $("body").prepend('<div name="request-div" style="position: absolute;width: 100%;height: 100%;z-index: 5000;display: none;">'
            +'<img src="'+basePath+'/images/request-sending.gif" style="position: relative;top: 50%;left: 50%;width: 200px;height: 200px">'
            +'</div>');
    }
    $("body").find("[name='request-div']").show();
    if(typeof fn != 'function'){
        flavrShowByTime("回调必须是个函数,function", null, "danger", false);
        return;
    }
    if($(parameter).is("form")){
        parameter = $(parameter).serialize();
    }
    setTimeout(function () {
        $.ajax({
            url: url,
            type: type,
            dataType: "json",
            data: parameter,
            success: function (data) {
                $("body").find("[name='request-div']").hide();
                if (data.ret == 500) {
                    fn(data);
                } else if (data.ret == 404) {
                    console.log("出错额。。。。404")
                } else if (data.ret == 600) {
                    location.href = basePath + "/user/logout";
                } else {
                    fn(data);
                }
            },
            error: function (data) {
                $("body").find("[name='request-div']").hide();
                console.log("出错la。。。。")
                console.log(data.status);
            }
        });
    },200)

}

/* 数字变化动画 */
function numAnimate(param) {
    param = $.extend({
        el: $(),  // jquery对象
        newNum: 0, // 新的数字
        fixNum: 0,  // 保留两位小数
        unit: '',   // 单位
        totalTime: 1000,   // 动画时间1000ms
        interval: 20   // 间隔时间20s
    }, param);
    var oldNum = parseFloat(param.el.text());
    var count = param.totalTime / param.interval;
    var dValue = (param.newNum - oldNum) / count;
    var flag = 0;
    var timer = setInterval(function () {
        oldNum += dValue;
        param.el.text(oldNum.toFixed(param.fixNum) + param.unit);
        flag++;
        if (flag >= count) {
            param.el.text(parseFloat(param.newNum).toFixed(param.fixNum) + param.unit);
            clearInterval(timer);
        }
    }, param.interval);
}

/**
 *
 * @param obj  --文件上传的form, fn  回调
 * url  上传路径
 */
function fileUplod(url,obj,fn){
   if( typeof fn != 'function'){
        return null;
   }
   if($("body").find("[name='request-div']")){
       var basePath = $("#basePath").val();
       $("body").prepend('<div name="request-div" style="position: absolute;width: 100%;height: 100%;z-index: 5000;display: none;">'
           +'<img src="'+basePath+'/images/request-sending.gif" style="position: relative;top: 50%;left: 50%;width: 200px;height: 200px">'
           +'</div>');
   }
    $("body").find("[name='request-div']").show();
   var formData = new FormData($(obj)[0]);
    setTimeout(function () {
        $.ajax({
            type : "POST",
            url: url,
            data :formData,//整个表单提交
            dataType : "json",
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success : function(data) {
                try {
                    if (data.ret == 200) {
                        $("body").find("[name='request-div']").hide();
                        fn(data.data);
                    } else {
                        new $.flavr({content:data.msg,closeOverlay:true,closeEsc:true,autoclose:true,timeout:1500,buttons:[{text:'确定',style:'danger'}]});
                    }
                } catch (error) {
                    new $.flavr({content:data.msg,closeOverlay:true,closeEsc:true,autoclose:true,timeout:1500,buttons:[{text:'确定',style:'warning'}]});
                }
            },
            error: function(data){
                $("body").find("[name='request-div']").hide();
            }
        });
    }, 200)
}

function isFileUpload(form,fn){
    var flag = false;
    var url = basePath + "/fileUpload/fileUploadForWeChat";
    $($(form).find("[name='files']")).each(function (){
        if($(this).val()!= ""){
            flag=true;
        }
    })
    if(flag){
        fileUplod(url,$(form),function (fileList){
            fn(fileList);
        });
    }else{
        fn([]);
    }
}

function scoreText(score){
    var text = "";
    switch (score){
        case 1: 
            text = "不满意"
            break;
        case 2:
            text = "不太满意"
            break;
        case 3:
            text = "一般"
            break;
        case 4:
            text = "比较满意"
            break;
        case 5: 
            text = "满意"
            break;
    }
    return text;
}
